<template>
  <div class="detail">
    <h4 class="detail-title" v-if="isCredit">
      <span>贷中风控数据</span>
      <span style="font-size: 16px; font-weight: normal; float: right">数据更新于：{{ dataTime }}</span>
    </h4>
    <h4 class="detail-title" v-else>准入风控数据</h4>

    <!-- 搜索栏 -->
    <el-form v-if="isCredit">
      <el-form-item label="" style="margin-bottom: 2px">
        <el-select v-model="afterLoanTime" clearable @change="submitDzMonth">
          <el-option v-for="(item, index) in dzMonthList" :key="index" :label="item" :value="item"></el-option>
        </el-select>
      </el-form-item>
    </el-form>

    <!-- 最基础数据 -->
    <CompanyInfodz v-on:change-lock="changeLock" v-if="isCredit" :afterLoanRsp="afterLoanRsp" :baseInfo="baseInfo">
    </CompanyInfodz>
    <CompanyInfo
      :riskInfoRsp="riskInfoRsp"
      :current="current"
      :isCredit="isCredit"
      :disableUpdateBtn="disableUpdateBtn"
      :baseInfo="baseInfo"
      v-else
    ></CompanyInfo>

    <!-- 三张表格 -->
    <section class="detail-table mb20" v-if="isCredit">
      <div>
        <RebateRegionCount :rebateRegionCount="rebateRegionCount"></RebateRegionCount>
      </div>
      <div>
        <RebateCommodityCount :rebateCommodityCount="rebateCommodityCount"></RebateCommodityCount>
      </div>
      <div v-if="$route.query.isFromEnterprise">
        <DrawbackInfo :drawbackInfo="drawbackInfo"></DrawbackInfo>
      </div>
    </section>
    <h6 class="mb10">其他数据</h6>
    <!-- 4个Tab切换 -->
    <nav class="common-nav mb20">
      <h2
        style="width: 120px"
        class="common-nav__title"
        :class="item.id === activeIndex ? 'tab_active' : ''"
        @click="switchNav(item)"
        v-for="(item, index) in navList"
        :key="index"
      >
        {{ item.name }}
      </h2>
    </nav>
    <main>
      <BaseInfo :baseInfo="companyInfo" v-show="activeIndex === 1"></BaseInfo>
      <TaxRebatesData class="mb10" v-show="activeIndex === 2"></TaxRebatesData>
      <CompanyInfo
        :riskInfoRsp="riskInfoRsp"
        :isCredit="isCredit"
        :current="current"
        :baseInfo="baseInfo"
        v-if="isCredit"
        v-show="activeIndex === 10"
      ></CompanyInfo>
      <!-- 搜索栏 -->
      <!--      <el-form v-show="activeIndex === 3" inline v-if="$route.query.isFromEnterprise">
        <el-form-item label="贷中数据所属月份" style="margin-bottom: 2px">
          <el-select v-model="searchTime" clearable>
            <el-option v-for="(item, index) in monthList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <slot name="footer">
          <el-form-item class="common-search__footer" style="margin-bottom: 2px">
            <span @click="submitMonth">搜索</span>
          </el-form-item>
        </slot>
      </el-form>-->
      <el-form v-show="activeIndex === 3" inline>
        <el-form-item label="贷中数据所属月份" style="margin-bottom: 2px">
          <el-select v-model="searchTime" clearable>
            <el-option v-for="(item, index) in monthList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <slot name="footer">
          <el-form-item class="common-search__footer" style="margin-bottom: 2px">
            <span @click="submitMonth">搜索</span>
          </el-form-item>
        </slot>
      </el-form>
      <TaxDeclaration
        class="mb10"
        :taxDeclaration="taxDeclaration"
        :showTime="TaxDeclarationTime"
        v-show="activeIndex === 3"
      ></TaxDeclaration>

      <!-- 搜索栏 -->
      <el-form v-show="activeIndex === 4" inline v-if="$route.query.isFromEnterprise">
        <el-form-item label="贷中数据所属月份" style="margin-bottom: 2px">
          <el-select v-model="searchTime" clearable>
            <el-option v-for="(item, index) in threeMonthList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <slot name="footer">
          <el-form-item class="common-search__footer" style="margin-bottom: 2px">
            <span @click="submitYear1">搜索</span>
          </el-form-item>
        </slot>
      </el-form>
      <AssetsLiabilitiesInfo
        class="mb10"
        :showTime="assetsLiabilitiesInfoTime"
        :assetsLiabilitiesInfo="assetsLiabilitiesInfo"
        v-show="activeIndex === 4"
      ></AssetsLiabilitiesInfo>

      <!-- 搜索栏 -->
      <el-form v-show="activeIndex === 5" inline v-if="$route.query.isFromEnterprise">
        <el-form-item label="贷中数据所属月份" style="margin-bottom: 2px">
          <el-select v-model="searchTime" clearable>
            <el-option v-for="(item, index) in threeMonthList" :key="index" :label="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
        <slot name="footer">
          <el-form-item class="common-search__footer" style="margin-bottom: 2px">
            <span @click="submitYear2">搜索</span>
          </el-form-item>
        </slot>
      </el-form>
      <Profit class="mb10" v-show="activeIndex === 5" :showTime="profitTime" :profit="profit"></Profit>
    </main>
    <!-- 股东信息 -->
    <ShareholdersInfo v-show="activeIndex === 1" class="mt10" :shareholdersInfo="shareholdersInfo"></ShareholdersInfo>
  </div>
</template>

<script>
import CompanyInfodz from './CompanyInfo/CompanyInfodz.vue'
import CompanyInfo from './CompanyInfo/index.vue'
import RebateRegionCount from './RebateRegionCount/index.vue'
import RebateCommodityCount from './RebateCommodityCount/index.vue'
import DrawbackInfo from './DrawbackInfo/index.vue'
import BaseInfo from './BaseInfo/index.vue'
import TaxDeclaration from './TaxDeclaration/index.vue'
import AssetsLiabilitiesInfo from './AssetsLiabilitiesInfo/index.vue'
import Profit from './Profit/index.vue'
import ShareholdersInfo from './ShareholdersInfo/index.vue'
import TaxRebatesData from '@/components/RiskControl/TaxRebatesData/index.vue'
import { rebateTypeObj, taxPayerTypeObj, logoutTypeObj } from '@/constants/riskControlModel.js'

export default {
  name: 'RiskControl',
  components: {
    CompanyInfo,
    RebateRegionCount,
    RebateCommodityCount,
    DrawbackInfo,
    BaseInfo,
    TaxDeclaration,
    AssetsLiabilitiesInfo,
    Profit,
    ShareholdersInfo,
    TaxRebatesData,
    CompanyInfodz,
  },
  props: {
    isCredit: Boolean,
    disableUpdateBtn: Boolean,
  },
  data() {
    return {
      afterLoanTime: '',
      activeIndex: 1,
      navList: this.$route.query.isFromEnterprise
        ? [
            { name: '企业基础信息', id: 1 },
            // { name: '纳税申报表', id: 3 },
            // { name: '资产负债表', id: 4 },
            // { name: '利润表', id: 5 },
          ]
        : [
            { name: '企业基础信息', id: 1 },
            { name: '历史退税数据', id: 2 },
            // { name: '纳税申报表', id: 3 },
            // { name: '资产负债表', id: 4 },
            // { name: '利润表', id: 5 },
          ],
      searchTime: '',
      monthList: [],
      threeMonthList: [],
      dzMonthList: [],
      // 基础信息/企业信息
      baseInfo: {},
      // 贷中信息
      afterLoanRsp: {},
      // 核心风控数据
      riskInfoRsp: {},
      // 企业信息
      companyInfo: [],
      // 纳税申报表
      taxDeclaration: {},
      // 纳税申报时间区间
      TaxDeclarationTime: {
        taxPeriodStart: '',
        taxPeriodEnd: '',
      },
      // 资产负债表
      assetsLiabilitiesInfo: [],
      // 资产负债时间
      assetsLiabilitiesInfoTime: { assetsPeriodStart: '', assetsPeriodEnd: '' },
      // 利润表
      profit: [],
      // 利润时间区间
      profitTime: { profitPeriodStart: '', profitPeriodEnd: '' },
      // 退税项下关单贸易国数据统计(近1年top5数据)
      rebateRegionCount: [],
      // 退税项下关单商品类别数据统计(近1年top5数据)
      rebateCommodityCount: [],
      // 上月退税数据
      drawbackInfo: [],
      // 股东信息
      shareholdersInfo: [],
      // 当前页面
      current: '',
      // 外贸融更新时间
      dataTime: '',
      // 默认值
      defaultTime: '',
    }
  },
  methods: {
    changeLock() {
      this.getMonthRequest('1')
      this.getDetailRequest()
    },
    switchNav(item) {
      this.searchTime = ''
      if (this.activeIndex === item.id) return
      this.activeIndex = item.id
    },
    async submitDzMonth() {
      await this.getDetailRequest('dzMonth')
    },
    async submitMonth() {
      await this.getDetailRequest('month')
    },
    async submitYear1() {
      await this.getDetailRequest('year1')
    },
    async submitYear2() {
      await this.getDetailRequest('year2')
    },
    async getDetailRequest(param) {
      const res = await this.$http.get('/risk/info', {
        params: {
          uscCode: this.$route.query.uscCode,
          queryType: this.$route.query.isFromEnterprise ? 1 : 2,
          searchTime: this.searchTime,
          afterLoanTime: param === 'dzMonth' && !this.afterLoanTime ? this.defaultTime : this.afterLoanTime,
        },
      })

      this.dataTime = res.dataTime ? res.dataTime : ''
      this.riskInfoRsp = res.riskInfoRsp ? res.riskInfoRsp : {}
      this.afterLoanRsp = res.afterLoanRsp ? res.afterLoanRsp : {}
      this.baseInfo = res.companyInfo
      // 企业信息
      this.resolveCompanyInfo(res.companyInfo)
      let flag = this.navList.find(o => o.id === 10)
      if (this.isCredit && !flag) {
        this.navList.push({ name: '准入风控数据', id: 10 })
      }

      // 纳税申报表
      if (!param || param === 'month') this.resolveTaxDeclaration(res.taxDeclaration)
      // 资产负债表
      if (!param || param === 'year1') this.resolveAssetsLiabilitiesInfo(res.assetsLiabilitiesInfo)
      // 利润表
      if (!param || param === 'year2') this.resolveProfitData(res.profit)
      this.rebateRegionCount = res.rebateRegionCount
      this.rebateCommodityCount = res.rebateCommodityCount

      if (res.drawbackInfo) {
        this.drawbackInfo =
          res.drawbackInfo.length > 1 ? [res.drawbackInfo[res.drawbackInfo.length - 1]] : res.drawbackInfo
      }

      this.shareholdersInfo = res && this.resolveShareholderInfo(res.shareholderInfo)
      if (!param || param === 'month') {
        this.TaxDeclarationTime.taxPeriodStart = res.taxPeriodStart
        this.TaxDeclarationTime.taxPeriodEnd = res.taxPeriodEnd
      }
      if (!param || param === 'year1') {
        this.profitTime.profitPeriodStart = res.profitPeriodStart
        this.profitTime.profitPeriodEnd = res.profitPeriodEnd
      }
      if (!param || param === 'year2') {
        this.assetsLiabilitiesInfoTime.assetsPeriodStart = res.assetsPeriodStart
        this.assetsLiabilitiesInfoTime.assetsPeriodEnd = res.assetsPeriodEnd
      }
    },
    resolveShareholderInfo(shareholderInfo) {
      if (shareholderInfo && shareholderInfo.length) {
        shareholderInfo.forEach(item => {
          item.identificationTypeText = item.identificationType === '0' ? '身份证' : '--'
        })
        return shareholderInfo
      }
      return []
    },
    resolveCompanyInfo(companyInfo) {
      this.companyInfo = [
        {
          rightTitle: '企业名称',
          rightValue: companyInfo.tenantName,
          leftTitle: '社会信用码',
          leftValue: companyInfo.uscCode,
        },
        {
          rightTitle: '联系电话',
          rightValue: companyInfo.telephone,
          leftTitle: '电子邮箱',
          leftValue: companyInfo.postalCode,
        },
        {
          rightTitle: '注册地址',
          rightValue: companyInfo.registeredAddress,
          leftTitle: '生产经营地址',
          leftValue: companyInfo.productionSite,
        },
        {
          rightTitle: '法定代表人',
          rightValue: companyInfo.legalRepresentative,
          leftTitle: '法定代表人电话',
          leftValue: companyInfo.legalRepresentativeTelephone,
        },
        {
          rightTitle: '法定代表人身份证',
          rightValue: companyInfo.legalRepresentativeNo,
          leftTitle: '开业日期',
          leftValue: companyInfo.openingTime,
        },
        {
          rightTitle: '注册资金',
          rightValue: companyInfo.registeredCapital,
          leftTitle: '经营期限(年)',
          leftValue:
            companyInfo.operationStart &&
            companyInfo.operationStart + '-' + companyInfo.operationEnd &&
            companyInfo.operationEnd,
        },
        {
          rightTitle: '是否注销',
          rightValue: logoutTypeObj[companyInfo.logoutType] || '--',
          leftTitle: '注销日期',
          leftValue: companyInfo.logoutTime,
        },
        {
          rightTitle: '主管税务机关',
          rightValue: companyInfo.taxAuthorityName,
          leftTitle: '经营者类型',
          leftValue: '--',
        },
        {
          rightTitle: '企业类型',
          rightValue: companyInfo.registerType,
          leftTitle: '登记注册类型',
          leftValue: companyInfo.registerType,
        },

        {
          rightTitle: '所属行业',
          rightValue: companyInfo.tradeCode,
          leftTitle: '纳税人类型',
          leftValue: taxPayerTypeObj[companyInfo.taxPayerType] || '--',
        },
        {
          rightTitle: '隶属关系',
          rightValue: companyInfo.subjectionType,
          leftTitle: '纳税信用等级',
          leftValue: companyInfo.creditRating,
        },
        { rightTitle: '是否零税率', rightValue: companyInfo.zeroTaxRate, leftTitle: '工商登记号', leftValue: '--' },
        {
          rightTitle: '退税计算方式',
          rightValue: rebateTypeObj[companyInfo.rebateType] || '--',
          leftTitle: '财务负责人',
          leftValue: companyInfo.financialOfficer,
        },
        {
          rightTitle: '财务负责人电话',
          rightValue: companyInfo.financialOfficerPhone,
          leftTitle: '财务负责人身份证号',
          leftValue: companyInfo.financialOfficernNo,
        },
        {
          rightTitle: '分类等级管理',
          rightValue: companyInfo.managementLevel,
          leftTitle: '出口备案日期',
          leftValue: companyInfo.exportRecordTime,
        },
        {
          rightTitle: '首次申报年月',
          rightValue: companyInfo.firstDeclarationYear,
          leftTitle: '累计退税申报次数',
          leftValue: companyInfo.declareNumber,
        },
      ]
    },
    // 处理纳税申请表数据，如无数据，直接隐藏tab
    resolveTaxDeclaration(obj) {
      if (!obj.generalMonth && !obj.generalTotal && !obj.refundMonth && !obj.refundTotal) {
        if (this.navList.findIndex(item => item.id === 3) !== -1) {
          this.navList.splice(
            this.navList.findIndex(item => item.id === 3),
            1
          )
        }
        this.taxDeclaration = {}
        this.activeIndex = 1
      } else {
        if (!this.navList.find(item => item.id === 3)) {
          this.navList.push({ name: '纳税申报表', id: 3 })
        }
        this.taxDeclaration = obj
      }
    },
    // 资产负债表数据处理
    resolveAssetsLiabilitiesInfo(array) {
      if (array && !array.length) {
        if (this.navList.findIndex(item => item.id === 4) !== -1) {
          this.navList.splice(
            this.navList.findIndex(item => item.id === 4),
            1
          )
        }
        this.assetsLiabilitiesInfo = []
        this.activeIndex = 1
      } else {
        if (!this.navList.find(item => item.id === 4)) {
          this.navList.push({ name: '资产负债表', id: 4 })
        }
        this.assetsLiabilitiesInfo = [
          {
            item: '行次',
            assetName: '资产',
            assetEndBalance: '期末余额',
            assetStartBalance: '年初余额',
            equityName: '负债和所有者权益(或股东权益)',
            equityEndBalance: '期末余额',
            equityStartBalance: '年初余额',
          },
          ...array,
        ]
      }
    },
    // 利润表数据处理
    resolveProfitData(array) {
      if (array && !array.length) {
        if (this.navList.findIndex(item => item.id === 5) !== -1) {
          this.navList.splice(
            this.navList.findIndex(item => item.id === 5),
            1
          )
        }
        this.profit = []
        this.activeIndex = 1
      } else {
        if (!this.navList.find(item => item.id === 5)) {
          this.navList.push({ name: '利润表', id: 5 })
        }
        this.profit = [
          { item: '行次', projectName: '项目', currentAmount: '本月数', cumulativeAmount: '本年累计数' },
          ...array,
        ]
      }
    },
    async getMonthRequest(type) {
      let _ = this
      this.monthList = []
      this.threeMonthList = []
      this.dzMonthList = []
      const res = await this.$http.get('/risk/date_list', {
        params: {
          uscCode: this.$route.query.uscCode,
          type,
        },
      })
      res.forEach(item => {
        if (item.type === '1') {
          _.monthList.push(item.date)
        } else if (item.type === '2') {
          _.threeMonthList.push(item.date)
        } else if (item.type === '3') {
          _.dzMonthList.push(item.date)
          if (_.dzMonthList.length > 0) {
            /*_.afterLoanTime = _.dzMonthList[0]*/
            _.afterLoanTime = _.dzMonthList[_.dzMonthList.length - 1]
            _.defaultTime = JSON.parse(JSON.stringify(_.dzMonthList[_.dzMonthList.length - 1]))
          }
        }
      })
      await this.getDetailRequest()
    },
  },
  mounted() {
    if (this.$route.query.appCode === 'WMR') {
      this.current = this.$route.path.indexOf('platform-audit-detail') > 0 ? 'PA' : ''
      this.getMonthRequest(this.isCredit ? '2' : '1')
    }
  },
}
</script>

<style lang="scss" scoped>
.detail {
  &-title {
    font-size: $f-s-20;
    margin-bottom: 10px;
  }
  &-block {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    color: $gray;
    font-size: $f-s-16;
    margin-bottom: 8px;
    > p {
      width: 33.33%;
      margin-bottom: 10px;
    }
  }
}
.common-search__footer {
  span {
    display: inline-block;
    text-align: center;
    border-radius: 1px;
    width: 136px;
    height: 36px;
    line-height: 36px;
    cursor: pointer;
    &:first-child {
      background: $blue;
      color: $white;
      border: 1px solid transparent;
    }
  }
}
</style>
